<template>
    <div>
        <el-row>
            <el-tabs
                ref="filterTabs"
                v-model="activeName"
                @tab-click="listTabChange"
                type="card"
            >
                <el-tab-pane name="myIssues">
                    <span slot="label">
                        <i class="el-icon-date"></i> 待会诊
                        <el-badge
                            v-if="myIssuesCount > 0"
                            :value="myIssuesCount"
                            class="tab-content-badge"
                        ></el-badge>
                    </span>
                </el-tab-pane>
                <el-tab-pane name="myFinish">
                    <span slot="label">
                        <i class="el-icon-date"></i> 已完成
                        <el-badge
                            v-if="myFinishCount > 0"
                            :value="myFinishCount"
                            class="tab-content-badge"
                        ></el-badge>
                    </span>
                </el-tab-pane>
                <el-tab-pane name="myInvited">
                    <span slot="label">
                        <i class="el-icon-date"></i> 我的邀请
                        <el-badge
                            v-if="myInvitedCount > 0"
                            :value="myInvitedCount"
                            class="tab-content-badge"
                        ></el-badge>
                    </span>
                </el-tab-pane>
                <el-tab-pane name="myFinal">
                    <span slot="label">
                        <i class="el-icon-date"></i> 我的终审
                        <el-badge
                            v-if="myFinalCount > 0"
                            :value="myFinalCount"
                            class="tab-content-badge"
                        ></el-badge>
                    </span>
                </el-tab-pane>
            </el-tabs>
        </el-row>
        <div>
            <!--筛选条件-->
        </div>
        <base-table
            ref="consultationTable"
            v-loading="!consultationTable.isReady"
            :data="consultationTable.data"
            :header="consultationTable.header"
            :operation="consultationTable.operation"
            :pageInfo="consultationTable.pageInfo"
            :buttonVisibleFunc="diagnosisTableButtonVisibleFunc"
            :pageSizes="[5, 10, 15]"
            @handleClick="consultationTableButtonClick"
            @pageJumpTo="diagnosisTablePageJumpTo"
            @sizeChange="consultationTableSizeChange"
        >
        </base-table>
    </div>
</template>

<script>
import BaseTable from '@/templates/components/BaseTable'
import moment from 'moment/moment'
import _ from 'lodash'
import { serviceStatusMap, ordersStatusMap } from '@/config/baseData.js'
export default {
  name: 'DiagnosisDispatch',
  components: {
    BaseTable
  },
  data() {
    return {
      myIssuesCount: 0, //医生待会诊角标
      myFinishCount: 0, //医生已会诊角标
      myInvitedCount: 0, //医生邀请角标
      myFinalCount: 0, //医生终审角标
      permissionGroupList: this.$store.state.permissionList, // 权限列表数据结构
      uesrId: this.$store.state.user.id,
      orderId: '',
      patientsId: '',
      doctorsTable: {
        isReady: false,
        data: [],
        header: [
          {
            label: '姓名',
            prop: 'name',
            width: '80'
          },
          {
            label: '性别',
            prop: 'genderName',
            width: '80'
          },
          {
            label: '医生职称',
            prop: 'positionName',
            width: '150'
          },
          {
            label: '医生职级',
            prop: 'medicalTitleName',
            width: '150'
          },
          {
            label: '所属医院',
            prop: 'institutionName'
          },
          {
            label: '电话',
            prop: 'phone'
          }
        ],
        operation: [
          {
            label: '分配',
            functionKey: 'doctorsTableAssign'
          }
        ],
        pageInfo: {
          page: 1,
          size: 15,
          total: 0
        }
      },
      doctorsDialog: {
        visible: false
      },
      // 所需字典对应表
      //   dictRequestMap: [
      //     {
      //       code: 'PConsultType',
      //       arrayKey: 'ConsultationsType'
      //     }
      //   ],
      checkCategoryList: [],
      sexKindList: [
        { id: 0, name: '女' },
        { id: 1, name: '男' }
      ],
      specimenCategoryList: [],
      showExpansion: false,
      consultationTable: {
        isReady: false,
        data: [],
        header: [
          {
            label: '订单ID',
            prop: 'consultationSerialNumber',
            width: '120'
          },
          {
            label: '订单号',
            prop: 'serialNumber',
            width: '120'
          },
          {
            label: '申请类型',
            prop: 'orderTypeName',
            width: '120'
          },
          {
            label: '诊断状态',
            width: '120',
            prop: 'serviceStatus',
            isRender: true,
            render: (h, params) => {
              let mColor = params.row.serviceStatusId === 2 ? 'red' : '#000000'
              return h(
                'span',
                {
                  style: {
                    color: mColor
                  }
                },
                params.row.serviceStatus
              )
            }
          },
          {
            label: '订单状态',
            prop: 'ordersStatus',
            width: '120'
          },
          {
            label: '申请时间',
            prop: 'createTime',
            width: '152'
          },
          {
            label: '患者姓名',
            prop: 'name',
            width: '120'
          },
          {
            label: '患者性别',
            prop: 'sexName',
            width: '120'
          },
          {
            label: '年龄',
            prop: 'ageData',
            width: '80'
          },
          {
            label: '病区',
            prop: 'ward'
          },
          {
            label: '床号',
            prop: 'bedNo'
          },
          {
            label: '会诊类型',
            prop: 'consultationType',
            width: '180'
          },
          {
            label: '取材部位',
            prop: 'simplePartId',
            width: '120'
          },
          {
            label: '标本类型',
            prop: 'simpleKindId',
            width: '120'
          },
          {
            label: '送检医院',
            prop: 'sendingHospitalName',
            width: '120'
          },
          {
            label: '送检医生',
            prop: 'sendingDoctor',
            width: '120'
          },
          {
            label: '送检医生电话',
            prop: 'sendingDoctorPhone',
            width: '140'
          },
          {
            label: '会诊医院',
            prop: 'serviceCenterName',
            width: '120'
          },
          {
            label: '专家诊断时间',
            prop: 'diagnosisTime',
            width: '140'
          },
          {
            label: '诊断专家',
            prop: 'diagnosisExpert',
            width: '120'
          },
          {
            label: '邀请专家',
            prop: 'inviteExperts',
            width: '120'
          },
          {
            label: '中心审核时间',
            prop: 'centerAuditTime',
            width: '140'
          },
          {
            label: '中心审核专家',
            prop: 'centerAuditExpert',
            width: '140'
          },
          //   {
          //     label: '是否录入',
          //     prop: 'extrasRecorded',
          //     width: '108'
          //   },
          {
            label: '快递总数',
            prop: 'expressCount',
            width: '108'
          },
          {
            label: '未签收数',
            prop: 'receiveWithoutSignInCount',
            width: '108'
          },

          {
            label: '陪诊通知',
            prop: 'companyStatus',
            width: '120'
          },
          {
            label: '联系人姓名',
            prop: 'contactName',
            width: '130'
          },
          //   {
          //     label: '联系人电话',
          //     prop: 'contactCellphone',
          //     width: '130'
          //   },
          {
            label: '联系人微信',
            prop: 'contactWeChat',
            width: '130'
          },
          {
            label: '送检人',
            prop: 'sender',
            width: '95'
          },
          {
            label: '退回原因',
            prop: 'returnReason',
            width: '120'
          }
        ],
        operation: [
          // {
          //   label: '快递',
          //   functionKey: 'receive'
          // },
          // {
          //   label: '分配',
          //   functionKey: 'scheduling'
          // },
          // {
          //   label: '退回',
          //   functionKey: 'sendBack'
          // },
          // {
          //   label: '支付详情',
          //   functionKey: 'payDetails'
          // }
        ],
        pageInfo: {
          page: 1,
          size: 10,
          total: 0
        }
      },
      currentRowDocTor: '',
      diagnosisID: null,
      serviceStatusList: [
        { id: 0, name: '申请(已整理)' },
        { id: 1, name: '诊断中' },
        { id: 2, name: '诊断结束' },
        { id: 3, name: '退回' },
        { id: 4, name: '调度员退回' },
        { id: 5, name: '申请(未整理)' },
        { id: 6, name: '加做诊断中' }
      ],
      ordersStatusList: [
        { id: 0, name: '未支付' },
        { id: 1, name: '已支付' },
        { id: 2, name: '作废' },
        { id: 3, name: '加做项目未支付' },
        { id: 4, name: '加做项目已支付' },
        { id: 5, name: '支付失败' },
        { id: 6, name: '后续支付失败' },
        { id: 7, name: '退款中' },
        { id: 8, name: '部分退款中' },
        { id: 9, name: '部分退款' },
        { id: 10, name: '全部退款' },
        { id: 11, name: '待退款' }
      ],
      createdRange: [],
      filterForm: {
        type: 2,
        consultationSerialNumber: '',
        serialNumber: '',
        serviceStatus: 1,
        name: '',
        contact: '',
        doctor: '',
        sendDoctor: '', // 送检医生
        consultationType: '', // 会诊类型
        startAge: '',
        endAge: '',
        cardId: '',
        sex: '',
        sampleBody: '', // 取材部位
        sendDoctorTel: '', // 联系电话
        endOperationTime: '', // 结束时间
        startOperationTime: '' // 起始时间
      },
      activeName: 'myIssues'
    }
  },
  mounted() {
    this.doctorOperationPermission() //如果是医生登录操作只显示详情
    //this.dictionariesRequest()// 获取字典数据
    this.getElBadge()
  },
  computed: {},
  methods: {
    // 退回4
    sendBack(row) {
      this.$axios({
        method: 'GET',
        url: `orders/sendBack/${row.id}/0`
      }).then((res, err) => {
        if (res.data.code === 200) {
          this.$message.info(res.data.data.message)
          // this.diagnosisTableRequest()
        } else {
          throw new Error(err)
        }
      })
    },
    async getElBadge() {
      this.$axios({
        method: 'GET',
        url: `orders/list/by/docker/id/count`
      }).then((res, err) => {
        if (res.data.code === 200) {
          this.myFinishCount = res.data.listFindCompleted
          this.myIssuesCount = res.data.listFindForConsultation
          this.myInvitedCount = res.data.listFindMyInvitation
          this.myFinalCount = res.data.listFindMyFinal
        } else {
          throw new Error(err)
        }
      })
      this.filterForm.type = 2
      this.filterForm.serviceStatus = 1
      this.diagnosisTableRequest()
    },
    listTabChange(tab, event) {
      if (this.activeName == 'myFinish') {
        this.filterForm.type = 1
        this.filterForm.serviceStatus = 2
      } else if (this.activeName == 'myIssues') {
        this.filterForm.type = 2
        this.filterForm.serviceStatus = 1
      } else if (this.activeName == 'myInvited') {
        this.filterForm.type = 3
        this.filterForm.serviceStatus = ''
      } else if (this.activeName == 'myFinal') {
        this.filterForm.type = 4
        this.filterForm.serviceStatus = ''
      }
      this.diagnosisTableRequest() //诊断数据获取
    },
    //医生登录操作只显示详情
    doctorOperationPermission() {
      this.permissionGroupList.forEach((item, index) => {
        if (item.name == '院外会诊') {
          this.permissionGroupList[index].permissionList.forEach((it, num) => {
            if (
              it.code == 'consultation-diagnosis' &&
              this.permissionGroupList[index].permissionList.length == 1
            ) {
              this.consultationTable.operation = []
            }
          })
        }
      })
    },
    //获取分配医生
    doctorsTableDataRequest(orderId, serviceCenterId, patientsId) {
      this.doctorsTable.isReady = false
      this.$axios({
        method: 'GET',
        url: `/consultations/${serviceCenterId}/${patientsId}/invitation-experts`,
        params: {
          page: this.doctorsTable.pageInfo.page - 1,
          size: this.doctorsTable.pageInfo.size
        }
      }).then(res => {
        if (res && res.data.code === 200) {
          // 分页处理
          this.doctorsTable.pageInfo = {
            total: res.data.pageInfo.total,
            page: res.data.pageInfo.page + 1,
            size: res.data.pageInfo.size
          }
          // 数据处理
          this.doctorsTable.data = []
          if (res.data.data) {
            res.data.data.forEach((t, index) => {
              const user = {
                index,
                id: t.id,
                name: t.name,
                genderName: t.genderName,
                jobNumber: t.jobNumber,
                positionName: t.positionName,
                medicalTitleName: t.medicalTitleName,
                createTime: moment(t.createTime).format('YYYY-MM-DD'),
                statusName: t.status ? '冻结' : '正常',
                area: t.area,
                idCardStatusName: '',
                qualityStatusName: '',
                institutionName: t.institutionName,
                phone: t.phone,
                roleList: t.roles,
                status: t.status,
                orderId: orderId,
                patientsId: patientsId
              }
              this.doctorsTable.data.push(user)
            })
          }
        }
        this.doctorsTable.isReady = true
      })
    },
    doctorsTablePageJumpTo(val) {
      this.doctorsTable.pageInfo.page = val
      this.doctorsTableDataGet()
    },
    doctorsTableSizeChange(val) {
      this.doctorsTable.pageInfo.size = val
      this.doctorsTableDataGet()
    },
    doctorsTableButtonClick(functionKey, row) {
      this[functionKey](row)
    },
    // 请求字典信息
    dictionariesRequest() {
      this.dictRequestMap.forEach(map => {
        this.$axios({
          method: 'GET',
          url: '/dicts/list',
          params: {
            code: map.code,
            page: 0,
            size: 99
          }
        }).then(res => {
          if (res && res.data.code === 200) {
            this[map.arrayKey] = _.clone(res.data.data)

            if (map.code === 'SexKind') {
              this[map.arrayKey].push({
                id: '',
                name: '全部'
              })
            }
          }
        })
      })
    },

    search() {
      // 确定时间范围
      if (this.createdRange && this.createdRange.length > 0) {
        let createTimeStart = ''
        let createTimeEnd = ''
        ;[createTimeStart, createTimeEnd] = this.createdRange
        this.filterForm.endOperationTime = moment(createTimeEnd)
          .format('YYYY-MM-DD hh:mm:ss')
          .replace(' ', ' ')
        this.filterForm.startOperationTime = moment(createTimeStart)
          .format('YYYY-MM-DD hh:mm:ss')
          .replace(' ', ' ')
      }

      // 重置页码
      this.consultationTable.page = 1
      this.diagnosisTableRequest()
    },

    // 诊断数据获取
    async diagnosisTableRequest() {
      let that = this
      that.consultationTable.isReady = true
      // 过滤条件为已保存的 formTemp 中获取
      that.filterForm.size = that.consultationTable.pageInfo.size
      that.filterForm.page = that.consultationTable.pageInfo.page - 1
      const res = await that.$axios({
        method: 'POST',
        url: `/orders/list/by/docker/id`,
        data: that.filterForm
      })

      if (res && res.data.code === 200) {
        // 请求成功
        const result = res.data.rows
        // 分页信息
        that.consultationTable.pageInfo = {
          total: result.totalElements,
          page: result.pageable.pageNumber + 1,
          size: result.pageable.pageSize
        }
        // 查询结果数据
        let resContent = res.data.rows.content
        that.consultationTable.data = []
        if (resContent) {
          resContent.forEach((t, index) => {
            const item = {
              id: t.id,
              index,
              consultationSerialNumber: t.id,
              serialNumber: t.serialNumber,
              serviceStatusId: this.serviceStatusList[t.serviceStatus].id,
              serviceStatus: serviceStatusMap[t.serviceStatus],
              ordersStatus: ordersStatusMap[t.ordersStatus],
              extrasRecorded: t.extrasRecorded,
              expressCount: t.expressCount,
              receiveWithoutSignInCount: t.receiveWithoutSignInCount,
              serviceCenterName: t.serviceCenterName,
              serviceProject: t.institutionServicesInfo.name,
              amount: t.amount,
              name: t.patients[0].name,
              sexName: t.patients[0].sexName,
              ageData: t.patients[0].age,
              companyStatus: t.companyStatus == 0 ? '不陪诊' : t.companyStatus == 0 ? '陪诊' : '',
              consultationType:
                t.typeOfConsultationName === '冰冻'
                  ? t.frozenAppointmentTime + t.morningAndAfternoonName
                  : t.typeOfConsultationName,
              simpleKindId: t.patients[0].diagnosisHistory[0].specimenCategoryName,
              simplePartId: t.patients[0].diagnosisHistory[0].visceraName,
              contactName: t.patients[0].contactName,
              contactCellphone: t.patients[0].contactCellphone,
              contactWeChat: t.patients[0].contactWeChat,
              sendingHospitalName: t.sendingHospitalName,
              sendingDoctor: t.sendingDoctor,
              sendingDoctorPhone: t.sendingDoctorPhone,
              serviceCenterName: t.serviceCenterName,
              orderTypeName: t.orderType == 1 ? '机构申请' : t.orderType == 2 ? '个人申请' : '',
              bedNo: t.patients[0].diagnosisHistory[0].bedNo,
              ward: t.patients[0].diagnosisHistory[0].ward,
              //标本快递时间暂无
              //标本签收状态暂无
              //标本签收时间暂无
              fromTypeId: t.fromTypeId,
              createTime: t.createTime,
              diagnosisTime: that.getValue('diagnosisTime', t), //诊断时间
              diagnosisExpert: that.getValue('expertName', t), //诊断专家
              inviteExperts: that.getValue('inviteExperts', t), //邀请专家
              centerAuditTime: that.getValue('centerAuditTime', t), //中心审核时间
              centerAuditExpert: that.getValue('centerAuditExpert', t), //中心审核专家
              orderId: t.id,
              serviceCenterId: t.serviceCenterId,
              patientsId: t.patients[0].id,
              returnReason: t.returnReason
            }
            that.consultationTable.data.push(item)
          })
        }
      } else {
        that.$message.warning('请求失败')
      }

      that.consultationTable.isReady = true
    },
    getValue(value, item) {
      let mRValue = ''
      item.patients[0].expertDiagnosis.forEach(t => {
        if (t.type == 0) {
          if (value == 'expertName') {
            mRValue = t.expertName
          }
          if (value == 'diagnosisTime') {
            mRValue = t.expertDiagnosisTime
          }
        }
        if (t.type == 1) {
          if (value == 'inviteExperts') {
            mRValue += t.expertName + ','
          }
        }
        if (t.isFinal == 1) {
          if (value == 'centerAuditExpert') {
            mRValue = t.expertName
          }
          if (value == 'centerAuditTime') {
            mRValue = t.expertDiagnosisTime
          }
        }
      })
      if (value == 'inviteExperts') {
        mRValue = mRValue.substring(0, mRValue.length - 1)
      }
      return mRValue
    },
    diagnosisTableButtonVisibleFunc(functionKey, row) {
      switch (functionKey) {
        case 'delete':
          return row.currentLevel === 0
        case 'submission':
          return row.currentLevel === 0
        case 'cancelConsulation':
          return row.currentLevel === 1
        case 'reportView':
          return row.currentLevel === 3
        case 'collection':
          return row.collectionId === null
        case 'Cancelcollection':
          return row.collectionId !== null
        default:
          return true
      }
    },
    cancelConsulation(val) {
      try {
        this.loading = true
        this.$axios({
          method: 'get',
          url: `/consultations/consultationState?id=${val.id}&typeCode=0`
        }).then(
          res => {
            if (res && res.data.code === 200) {
              this.$message.info('成功取消')
              this.diagnosisTableRequest()
            }
          },
          err => {
            this.$message.success(`失败  ${err.response.data.message}`)
          }
        )
      } catch (e) {
        this.$message.info('请求失败')
      }
    },
    submission(val) {
      try {
        this.loading = true
        this.$axios({
          method: 'get',
          url: `/consultations/consultationState?id=${val.id}&typeCode=1`
        }).then(
          res => {
            if (res && res.data.code === 200) {
              this.$message.success('提交成功')
              this.diagnosisTableRequest()
            }
          },
          err => {
            this.$message.info(`用户验证  ${err.response.data.message}`)
          }
        )
      } catch (e) {
        this.$message.info('请求失败')
      }
    },
    diagnosisTablePageJumpTo(val) {
      this.consultationTable.pageInfo.page = val
      this.diagnosisTableRequest()
    },
    consultationTableSizeChange(val) {
      this.consultationTable.pageInfo.size = val
      this.diagnosisTableRequest()
    },
    consultationTableButtonClick(functionKey, row) {
      this[functionKey](row)
    },
    // 详情
    details(row) {
      this.$store.commit('setUArgs', {
        consultationId: row.id
      })
      this.$router.push('/consultation/detail')
      // if (row.currentLevel === 3) {
      //   this.$store.commit('setUArgs', {
      //     consultationId: row.id,
      //   });
      //   this.$router.push('/consultation/detail');
      // } else {
      //   this.$store.commit('setUArgs', {
      //     consultationId: row.id,
      //   });
      //   this.$router.push('/consultation/consultationEdit');
      // }
    },
    //支付详情
    payDetails(row) {
      this.$store.commit('setUArgs', {
        consultationId: row.id
      })
      this.$router.push('/consultation/payDetail')
    },
    // 签收
    receive(row) {
      this.$router.push({ name: 'ConsultationExpressList', params: { orderId: row.id } })
    },
    // 调度
    scheduling(row) {
      this.doctorsTableDataRequest(row.orderId, row.serviceCenterId, row.patientsId)
      this.doctorsDialog.visible = true
    },
    reportView(val) {
      const { state } = this.$store
      const { href } = this.$router.resolve({
        name: 'ConsultationReportView',
        path: '/detail/preview',
        query: {
          consultationSerialNumber: val.id,
          authorization: this.$store.state.authorization,
          userId: state.user.id
        }
      })
      window.open(href, '_blank')
    },
    delete(row) {
      this.$axios({
        method: 'delete',
        url: `/consultations/${row.id}`
      }).then((res, err) => {
        if (res.data.code === 200) {
          this.$message.success('删除成功!')
          this.diagnosisTableRequest()
        } else {
          this.$message.error('删除失败!')
          throw new Error(err)
        }
      })
    },
    collection(row) {
      this.$axios({
        method: 'POST',
        url: `/collections/${row.id}`
      }).then((res, err) => {
        if (res.data.code === 200) {
          this.$message.success('收藏成功!')
          this.diagnosisTableRequest()
        } else {
          this.$message.error('收藏失败!')
          throw new Error(err)
        }
      })
    },
    Cancelcollection(row) {
      this.$axios({
        method: 'DELETE',
        url: `/collections/${row.collectionId}`
      }).then((res, err) => {
        if (res.data.code === 200) {
          this.$message.success('成功取消收藏!')
          this.diagnosisTableRequest()
        } else {
          this.$message.error('收藏失败!')
          throw new Error(err)
        }
      })
    },
    // 表格 - 按钮点击
    doctorsTableButtonClick(functionKey, row) {
      this[functionKey](row)
    },
    //医生表格分配
    doctorsTableAssign(currentRowDocTor) {
      this.$confirm(`分配给${currentRowDocTor.name}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await this.$axios({
            method: 'GET',
            url: `/orders/${currentRowDocTor.orderId}/${currentRowDocTor.patientsId}/allocate/${currentRowDocTor.id}`
          })

          if (res && res.data.code === 200) {
            if (this.workingStatus === 'assigning') {
              this.$message.success('重新分配成功')
            } else {
              this.$message.success('分配成功')
            }
            this.doctorsDialog.visible = false
            this.diagnosisTableRequest()
          } else if (this.workingStatus === 'assigning') {
            this.$message.info('重新分配失败')
          } else {
            this.$message.warning('分配失败')
          }
        })
        .catch(() => {})
    },
    workingStatusChange() {
      this.diagnosisTableRequest()
    }
  }
}
</script>

<style scoped>
.tab-content-badge {
  top: 3px;
}
.expansion {
  width: 30px;
  height: 30px;
  display: inline;
  font-size: 28px;
  line-height: 30px;
  margin-top: 25px;
  vertical-align: middle;

  color: #00be8b;
  cursor: pointer;
}
.link-line {
  text-align: center;
}
</style>
